package com.xmlparse;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

/*dom4j解析xml文件*/
public class XmlParse {
    public static void main(String[] args) throws Exception {
        //1.首先获取一个解析器对象
        SAXReader saxReader = new SAXReader();
        //2.之后通过解析器把xml文件加载内存，返回文档对象document
        Document document = saxReader.read(new FileInputStream("Day18\\xml\\student.xml"));
        //3.获取根对象
        Element rootElement = document.getRootElement();
        //4.通过跟标签获取student标签
        //elements("标签名")不带参数，获取所以子标签 ；带参数，调用指定的所有子标签
        //返回一个集合对象
        List<Element> students = rootElement.elements();

        //装学生对象
        ArrayList<Student> list = new ArrayList<>();

        //5.遍历集合
        for (Element student : students) {
            //获取每一个student标签
            //System.out.println(student);

            //获取id属性
            Attribute attribute = student.attribute("id");
            //得到id值
            String id = attribute.getValue();

            //获取name标签
            Element nameElement = student.element("name");
            //得到name标签内容
            String name = nameElement.getText();
            
            //获取age标签
            Element ageElement = student.element("age");
            String age = ageElement.getText();

            Student s = new Student(id,name,Integer.parseInt(age));
            list.add(s);
        }
        for (Student student : list) {
            System.out.println(student);
        }
    }
}
